package org.lim.shared.websocket.service.strategy;

import org.lim.shared.websocket.model.PictureEditRequestMessage;
import org.lim.shared.websocket.model.PictureEditResponseMessage;
import org.lim.shared.websocket.model.enums.PictureEditActionEnum;
import org.lim.shared.websocket.model.enums.PictureEditMessageTypeEnum;
import org.lim.shared.websocket.service.PictureEditBroadcastService;
import org.lim.shared.websocket.service.PictureEditStateService;
import org.lim.domain.user.entity.User;
import org.lim.application.service.UserApplicationService;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;

@Component("editActionStrategy")
public class EditActionStrategy implements PictureEditMessageStrategy {
    
    @Resource
    private UserApplicationService userApplicationService;
    
    @Resource
    private PictureEditBroadcastService broadcastService;
    
    @Resource
    private PictureEditStateService stateService;
    
    @Override
    public void handleMessage(PictureEditRequestMessage requestMessage, WebSocketSession session, User user, Long pictureId) throws Exception {
        Long editingUserId = stateService.getEditingUserId(pictureId);
        String editAction = requestMessage.getEditAction();
        PictureEditActionEnum actionEnum = PictureEditActionEnum.getEnumByValue(editAction);
        
        if (actionEnum == null) {
            return;
        }
        
        // 确认是当前编辑者
        if (editingUserId != null && editingUserId.equals(user.getId())) {
            PictureEditResponseMessage responseMessage = new PictureEditResponseMessage();
            responseMessage.setType(PictureEditMessageTypeEnum.EDIT_ACTION.getValue());
            String message = String.format("%s执行%s", user.getUserName(), actionEnum.getText());
            responseMessage.setMessage(message);
            responseMessage.setEditAction(editAction);
            responseMessage.setUser(userApplicationService.getUserVO(user));
            
            // 广播给除了当前客户端之外的其他用户，否则会造成重复编辑
            broadcastService.broadcastToPicture(pictureId, responseMessage, session);
        }
    }
}